using System;
using System.IO;
using System.Text;

namespace Universe.Farm.Service.Mesages
{
    class MessageIO
    {
        public static IMessage Parse(byte[] raw)
        {
            using(MemoryStream mem = new MemoryStream(raw))
            using(BinaryReader r = new BinaryReader(mem, Encoding.UTF8))
            {
                byte type = r.ReadByte();
                IMessage message;
                if (type == 1)
                    message = new AnnounceMessage();

                else if (type == 2)
                    message = new LookupRequestMessage();

                else if (type == 3)
                    message = new ByeMessage();

                else if (type == 4)
                    message = new SetVisibilityMessage();

                else
                    throw new ArgumentException("Unknown message header " + type);

                message.Parse(r);
                return message;
            }
        }

        public static byte[] Serialize(IMessage message)
        {
            if (message == null)
                throw new ArgumentNullException("message");

            using(MemoryStream mem = new MemoryStream())
            using(BinaryWriter wr = new BinaryWriter(mem, Encoding.UTF8))
            {
                if (message is AnnounceMessage)
                    wr.Write((byte)1);

                else if (message is LookupRequestMessage)
                    wr.Write((byte)2);

                else if (message is ByeMessage)
                    wr.Write((byte)3);

                else if (message is SetVisibilityMessage)
                    wr.Write((byte)4);

                else
                    throw new NotSupportedException("Message " + message.GetType() + " is not supported");

                message.Serialize(wr);

                wr.Flush();
                return mem.ToArray();
            }
            
        }
    }
}
